<template>
    <div class="">
        <h4 class="margin_bottom20">商品列表</h4>
        <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="12">
                <el-button type="primary" size="small" @click="add"><i class="iconfont icon-plus"></i>新增</el-button>
                <!--<el-button type="primary" size="small" @click="delete" icon="delete">删除</el-button>-->
              </el-col>
            <el-col :span="6">
                <el-input placeholder="搜索..." size="small" v-model="searchKey"><el-button slot="append" icon="search" @click="loadData"></el-button></el-input>
            </el-col>
        </el-row>
        <template>
            <el-table :data="tableData" border style="width: 100%; text-align: center;margin-top:10px;" v-loading.body="loading">
                <!--<el-table-column type="selection"></el-table-column>-->
                <el-table-column prop="name" header-align="center" label="商品名称"></el-table-column>
                <!--<el-table-column prop="prdtDesc" header-align="center" label="产品简介"></el-table-column>-->
                <el-table-column label="产品图标" header-align="center">
                    <template scope="scope">
                        <img :src="tableData[scope.$index].avatar" style="width:100px;"></img>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="120">
                    <template scope="scope">
                        <el-button @click="view(tableData[scope.$index].id)" size="small">查看产品详情</el-button>
                        <el-button @click="edit(tableData[scope.$index].id)" size="small">修改</el-button>
                        <el-button @click="deleted(tableData[scope.$index].id)" size="small">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[20,50,100,200]"
                :page-size="limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </template>
        
        <!-- 表单弹窗 -->
        <el-dialog title="添加砍价商品" :visible.sync="dialogAddVisible" :show-close="false" before-close="beforeClose">

            <el-form :model="goods"  ref="addForm">
                <el-form-item label="商品名称" :label-width="formLabelWidth" prop="name"
                              :rules="[{ required: true, message: '名称不能为空'}]">
                    <el-input v-model="goods.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="商品图片" :label-width="formLabelWidth" prop="avatar"
                              :rules="[{ required: true, message: '商品图片不能为空'}]">
                    <el-upload class="avatar-uploader"
                        :action="uploadPath"
                        :show-file-list="false"
                        :on-success="setAvatar"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="goods.avatar" :src="goods.avatar" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="原价" :label-width="formLabelWidth" prop="origPrice"
                              :rules="[{ required: true, message: '原价不能为空'}, { type: 'number', message: '价格必须为数字'}]">
                    <el-input v-model.number="goods.origPrice" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="砍价最低价" :label-width="formLabelWidth" prop="lowerPrice"
                              :rules="[{ required: true, message: '砍价最低价不能为空'}, { type: 'number', message: '价格必须为数字'}]">
                    <el-input v-model.number="goods.lowerPrice" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="砍价价格方式" :label-width="formLabelWidth" prop="bargainType" :rules="[{ required: true, message: '砍价价格方式不能为空'}, { type: 'number', message: '价格必须为数字'}]">
                    <el-select v-model="goods.bargainType" placeholder="请选择" size="small">
                        <el-option :key="0" label="随机价格" :value="0"></el-option>
                        <el-option :key="1" label="固定价格" :value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="砍一刀价格" :label-width="formLabelWidth" prop="unitPrice" v-if="goods.bargainType == 1"
                              :rules="[{ required: true, message: '砍一刀价格不能为空'}, { type: 'number', message: '价格必须为数字'}]">
                    <el-input v-model.number="goods.unitPrice" auto-complete="off"></el-input>
                </el-form-item>

                <el-form-item label="砍一刀最低" :label-width="formLabelWidth" prop="unitPriceMin" v-if="goods.bargainType == 0"
                              :rules="[{ required: true, message: '砍一刀最低格不能为空'}, { type: 'number', message: '价格必须为数字'}]">
                    <el-input v-model.number="goods.unitPriceMin" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="砍一刀最高" :label-width="formLabelWidth" prop="unitPriceMax" v-if="goods.bargainType == 0"
                              :rules="[{ required: true, message: '砍一刀最高格不能为空'}, { type: 'number', message: '价格必须为数字'}]">
                    <el-input v-model.number="goods.unitPriceMax" auto-complete="off"></el-input>
                </el-form-item>

                <el-form-item label="库存" :label-width="formLabelWidth" prop="stock"
                              :rules="[{ required: true, message: '库存不能为空'}, { type: 'number', message: '库存必须为数字'}]">
                    <el-input v-model.number="goods.stock" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="活动时长（天）" :label-width="formLabelWidth" prop="duration"
                              :rules="[{ required: true, message: '活动时长不能为空'}, { type: 'number', message: '活动时长必须为数字'}]">
                    <el-input v-model.number="goods.duration" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="商品详情" :label-width="formLabelWidth" prop="content"
                              :rules="[{ required: true, message: '商品详情不能为空'}]">
                    <v-editor id="editor1" :input-content="inputContent" :upload-url="uploadURL" v-model="goods.content"></v-editor>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="reset('addForm')">取 消</el-button>
                <el-button type="primary" @click="submit('addForm')">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="产品详情" v-model="dialogViewVisible" :show-close="false">
            <table>
                <tr>
                    <td width="100">商品名称：</td>
                    <td>{{goods.name}}</td>
                </tr>
                <tr>
                    <td width="100">商品图片：</td>
                    <td><img :src="goods.avatar" class="avatar"></td>
                </tr>
                <tr>
                    <td width="100">原价：</td>
                    <td>{{goods.origPrice}}</td>
                </tr>
                <tr>
                    <td width="100">砍价最低价：</td>
                    <td>{{goods.lowerPrice}}</td>
                </tr>
                <tr>
                    <td width="100">砍价方式：</td>
                    <td>{{goods.bargainType == 0 ? '随机价格': '固定价格'}}</td>
                </tr>
                <tr v-if="goods.bargainType == 1">
                    <td width="100">砍一刀价格：</td>
                    <td>{{goods.unitPrice}}</td>
                </tr>
                <tr v-if="goods.bargainType == 0">
                    <td width="100">砍一刀最低：</td>
                    <td>{{goods.unitPriceMin}}</td>
                </tr>
                <tr v-if="goods.bargainType == 0">
                    <td width="100">砍一刀最高：</td>
                    <td>{{goods.unitPriceMax}}</td>
                </tr>
                <tr>
                    <td width="100">库存：</td>
                    <td>{{goods.stock}}</td>
                </tr>
                <tr>
                    <td width="100">活动时长：</td>
                    <td>{{goods.duration}}</td>
                </tr>
                <tr>
                    <td width="100" style="margin-top:100px;">商品详情：</td>
                    <td style="margin-top:100px;"><div v-html="goods.content"></div></td>
                </tr>
            </table>
        </el-dialog>
    </div>
</template>
<script>
import Editor from '../../components/editor.vue'
    export default {
        data (){
            return {
                tableData: [],
                currentPage: 1,
                total: 0,
                limit: 20,
                searchKey: '',
                loading: false,
                uploadPath: '',
                goods: {
                    id: '',
                    name: '',
                    content: '',
                    origPrice: '',
                    lowerPrice: '',
                    duration: '',
                    stock: '',
                    unitPrice: '',
                    avatar: '',
                    deleted: 1,
                    bargainType: 0,
                    unitPriceMin: '',
                    unitPriceMax: ''
                },
                dialogAddVisible: false,
                dialogViewVisible: false,
                formLabelWidth: '120px',
                inputContent: '',
                uploadURL: ''//编辑器的上传图片地址
            }
        },
        methods : {

            //pageSize 改变时会触发,就是limit改变时候触发
            handleSizeChange() {
                
            },

            //currentPage 改变时会触发
            handleCurrentChange(currentPage) {
                // console.log(currentPage);
                this.currentPage = currentPage;
                this.loadData();
            },
            loadData() {
                this.loading = true;
                this.$http.get(API.rootPath + "/goods", {params:{offset: this.limit*(this.currentPage - 1), limit: this.limit, searchKey: this.searchKey, companyId: localStorage.companyId}}).then((response) => {

                    this.tableData = response.body.data.rows;
                    this.total = response.body.data.total;
 
                    this.loading = false;
                }, (response) => {
                    // error callback
                }); 
            },
            add() {
                    
                this.initEntity();
                this.dialogAddVisible = true;
            },

            view(id) {
                var vm = this;
                //查询出指定id的商品，然后进入查看详情页面
                this.$http.get(API.rootPath + "/goods/" + id).then((response) => {
                    //console.log(response.body);

                    if(response.body.status == 0) {
                        this.goods = response.body.data;
                        this.inputContent = response.body.data.content;

                        vm.dialogViewVisible = true;
                    }
                });
            },
            deleted(id) {
                var vm = this;
                this.$confirm('确定删除吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete(API.rootPath + "/goods/" + id).then((response) => {
                        if(response.body.status == 0) {

                            vm.$message({
                                message: '删除成功',
                                type: 'success'
                            });

                            vm.loadData();
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });                
            },
            setAvatar(res, file) {
                console.log("上传成功了", res);
                this.goods.avatar = res;
            },
            beforeAvatarUpload(file) {
                // const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;
                // console.log("isJpg:", isJPG);
                // if (!isJPG) {
                //     this.$message.error('上传图片只能是 JPG 格式!');
                //     return;
                // }
                if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
                    return;
                }
                // return isJPG && isLt2M;
                return isLt2M;
            },
            submit(formName){

                var vm=this;

                //validate
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        var data = vm.goods;

                        this.$http.post(API.rootPath + "/goods", data, {emulateJSON: false}).then((response) => {
                            //console.log(response.body);

                            if(response.body.status == 0) {
                                vm.$message({
                                    message: '保存成功',
                                    type: 'success'
                                });
                                vm.dialogAddVisible = false;
                                vm.dialogEditVisible = false;

                                this.loadData();
                            }
                        });
                    } else {
                        //console.log('error submit!!');
                        return false;
                    }
                });
            },
            edit(id) {
                var vm = this;
                //查询出指定id的product，然后进入修改页面
                this.$http.get(API.rootPath + "/goods/" + id).then((response) => {
                    //console.log(response.body);

                    if(response.body.status == 0) {
                        this.goods = response.body.data;
                        this.inputContent = response.body.data.content;

                        vm.dialogAddVisible = true;
                    }
                });
            },

            /**
             * 重置表单，并关闭
             */
            reset(formName) {
                this.$refs[formName].resetFields();
                this.dialogAddVisible = false;
            },

            /**
             * 关闭之前弹出确认
             */
            beforeClose(done) {
                var vm = this;

                this.$confirm('确认关闭？')
                    .then(_ => {
                        vm.reset('addForm');
                        done();
                    })
                    .catch(_ => {});
                
            },

            initEntity() {
                this.goods = {
                    id: '',
                    name: '',
                    avatar: '',
                    content: '',
                    origPrice: '',
                    lowerPrice: '',
                    duration: '',
                    stock: '',
                    unitPrice: '',
                    deleted: 1,
                    bargainType: 0,
                    unitPriceMin: '',
                    unitPriceMax: ''
                }
            }
        },
                //引入文本编辑器那个组件
        components: {
            'v-editor': Editor
        },
        created() {
            this.loadData();
            this.uploadPath = API.rootPath + "/rap/images/avatars/good";
            this.uploadURL = API.rootPath + "/rap/images/editors/good";
        }
    }
</script>
<style>
.el-dialog--small {
    width: 60%;
}
</style>
